{% extends base.html %}

{% block head %}
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"/>

<script type="text/javascript" src="/static/js/string.js"></script>
<link rel="stylesheet" type="text/css" href="/static/lib/webuploader/webuploader.css">
<script type="text/javascript" src="/static/lib/webuploader/webuploader.nolog.min.js"></script>

<style type="text/css">
    .chat-box {
        /*background-color: #CCFF99;*/
    }

    .chat-msg-div {
        margin-top: 1rem;
        float: left;
        width: 100%;
    }

    .chat-avatar {
        color: #2092d9;
    }

    .finished-tag {
        color: #fff;
        background-color: green;
    }
    .in-progress {
        background-color: #f90;
    }

    .chat-msg {
        /*background-color: #99CCFF;*/
        padding: 0.3em;
        padding: 0.3rem;
        margin-top: 0.1rem;
        float: left;
        box-sizing: border-box;
    }
    .chat-msg-content {
        padding-left: 0.5rem;
        border-width: 5px;
        border-radius: 5px;
        word-wrap: break-word;
        word-break: break-all;
        /*background-color: #99CCFF;*/
    }
    .chat-msg-img {
        width: 180px;
    }
    .chat-msg-time {
        /*text-align: center;*/
        color: #888;
        margin: 0;
        font-size: 10px;
    }

    .input-box {
        /*position: relative;*/
        /*left: 0;*/
        /*right: 0;*/
        /*width: calc(100% - 5rem);*/
        width: 100%;
        outline: none;
    }

    .send-button {
        float: left;
        width: 4rem;
        margin-top: 0.5rem;
        margin-right: 0.5rem;
    }

    .right {
        float: right;
    }

</style>
{% end %}

{% block body %}
{% init key = "" %}
<script src="/static/lib/vue/vue-2.2.6.min.js"></script>

<div id="app" class="col-md-12">
    <div class="col-md-12">
        <a class="tab tab-link" href="/message?status=created">关注</a>
        <a class="tab tab-link" href="/message?status=all">全部</a>
        <!-- <a class="tab tab-link" href="/tools/message?status=minor">不紧急</a> -->
        <!-- <a class="tab tab-link" href="/tools/message?status=done">已完成</a> -->
    </div>

    <div class="input-div col-md-12">
        <textarea class="col-md-12 input-box" v-model="input" rows=4></textarea>
        <input type="button" name="" class="send-button btn" value="添加" @click="sendMessage()">
        <input type="file" id="filePicker" class="hide" multiple/>
        <input type="button" id="filePickerBtn" class="send-button btn" value="上传文件"/>
        <div id="uploadProgress" style="float: right;" ></div>
    </div>

    <div class="chat-box col-md-12">
        <div class="chat-msg-div" v-if="messageList.length == 0">
            空空如也~
        </div>
        <div class="chat-msg-div" v-for="message in messageList">
            <div class="chat-avatar col-md-12">
                <!-- {{! message.ctime }} -->
                <!-- <span class="tag-span" v-if="message.status==100">已完成</span> -->
            </div>
            <div class="chat-msg col-md-12">
                <template v-if="message.editable">
                    <textarea class="input-box col-md-12" v-bind:rows="message.content.count('\n')+3" v-model="message.content"></textarea>
                    <input type="button" value="更新" v-on:click="updateMessage(message)">
                    <input type="button" value="取消" v-on:click="message.editable = false" class="btn-cancel">
                </template>
                <div v-else>
                    <div v-if="message.link">
                        <a v-bind:href="message.link">{{! message.link }}</a>
                    </div>
                    <div v-if="message.imgSrc">
                        <a v-bind:href="message.imgSrc">
                            <img v-bind:src="message.imgSrc" class="chat-msg-img"/>
                        </a>
                    </div>
                    <div v-if="message.html" class="chat-msg-content" v-html="message.html">
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                <p class="chat-msg-time">
                    {{! message.ctime }}
                    <span class="tag-span in-progress" v-if="message.status==0">关注</span>
                    <a class="smallText" v-if="message.status!=100" v-bind:msg-id="message.id" href="javascript:void(0)" @click="finishMessage($event)">完成</a>
                    <a class="smallText" v-if="message.status==100" v-bind:msg-id="message.id" href="javascript:void(0)" @click="openMessage($event)">关注</a>
                    <a class="smallText" v-on:click="(message.editable = true) && console.log(message, messageList)" href="javascript:void(0)">编辑</a>
                    <a class="smallText" v-if="message.user==current_user" v-bind:msg-id="message.id" v-bind:msg-content="message.content" href="javascript:void(0)" style="color: red;" @click="deleteMessage($event)">删除</a> 
                </p>
                <hr/>
            </div>
        </div>
    </div>

    <div class="col-md-12">
        <p>
            <a class="x-page-link" href="#">共{{!page_max}}页/{{!amount}}条</a> 
            <a v-if="page > 1" class="x-page-link" v-bind:href="page_prev_url">上一页</a>
            <a class="x-page-link x-page-active" href="#">{{!page}}</a>
            <a v-if="page < page_max" class="x-page-link" v-bind:href="page_next_url">下一页</a>
        </p>
    </div>
</div>

<script type="text/javascript">
    function newMessage(content, user, status) {
        return {"content": content, user:user, status:status}
    }

    function wrapMessage(message) {
        message.editable = false;
        return message;
        var content = message.content;
        var reg = /file:\/\/([\S]+)\n*(.*)/gi;
        var parts = reg.exec(content);
        if (parts) {
            var path = parts[1];
            var text = parts[2];
            var lowerPath = path.toLowerCase();
            if (lowerPath.endsWith(".jpg") || lowerPath.endsWith(".jpeg") || 
                    lowerPath.endsWith(".png") || lowerPath.endsWith(".gif")) {
                message.imgSrc = path;
            } else {
                message.link = path;
            }
            message.html = text;
        } else {
            var html = content.replace(/(https*:\/\/[^ \t\r\n]+)/gi, '<a href="$1">$1</a>');
            html = html.replace(/\n/gi, "<br>");
            message.html = html;
        }
        return message;
    }

    var app = new Vue({
        el: "#app",
        data: {
            title: "消息",
            message: "Hello, Vue!",
            messageList: [newMessage("Welcome to chatroom")],
            person: {
                name:"Jhon",
                age: 20,
            },
            bindmessage: "页面加载于 " + new Date(),
            seen: false,
            rawHtml: "{{!message}}",
            url: "https://www.baidu.com",
            input: "",
            page_max: 2,
            page: 1,
            page_url: "/message?pagesize=20&page=",
            page_next_url:"#",
            page_prev_url:"#",
            current_user:"",
            status: "",
            amount: 0
        },
        methods: {

            init: function () {
                this.status = getUrlParams().status;
                this.page_url = "/message?status=%s&pagesize=20&key={{key}}&page=".format(this.status);
            },

            refreshMessage: function () {
                var self = this;
                var page = getUrlParams().page || 1;
                app.page = page;
                app.page_next_url = app.page_url + (parseInt(page)+1);
                app.page_prev_url = app.page_url + (page-1);
                $.get("/message/list", {pagesize:20,page:page,status:self.status,key:"{{key}}"}, function (respText) {
                    var data = respText;
                    app.page_max = data.page_max;
                    app.current_user = data.current_user;
                    if (data.code == "success") {
                        var messageList = [];
                        data.data.forEach(function (item, index) {
                            // console.log(item, index);
                            messageList.push(wrapMessage(item));
                        })
                        messageList.reverse();
                        self.messageList = messageList;
                        self.amount = data.amount;
                    }
                })
            },

            sendMessage: function () {
                if (this.input == "") {
                    return;
                }
                var self = this;
                $.post("/file/message/add", {content:self.input}, function (respText) {
                    var data = respText;
                    if (data.code == "success") {
                        var msg = wrapMessage(data.data);
                        self.messageList.push(msg);
                        self.input = "";
                    } else {
                        alert(data.message);
                    }
                    app.refreshMessage();
                }).fail(function (data) {

                })
            },

            deleteMessage: function (event) {
                var el = event.currentTarget;
                var self = this;
                var id = $(el).attr("msg-id");
                var content = $(el).attr("msg-content");
                var check = confirm("确认删除 '%s' ?".format(content));
                if (check) {                
                    $.post("/file/message/remove", {id: id}, function (resp) {
                        if (resp.code == "success") {
                            app.refreshMessage();
                        } else {
                            alert(data.message);
                        }
                    });
                }
            },

            finishMessage: function (event) {
                var el = event.currentTarget;
                var self = this;
                var id = $(el).attr("msg-id");
                $.post("/file/message/finish", {id: id}, function (resp) {
                    if (resp.code == "success") {
                        app.refreshMessage();
                    } else {
                        alert(data.message);
                    }
                });
            },

            openMessage: function (event) {
                var el = event.currentTarget;
                var self = this;
                var id = $(el).attr("msg-id");
                $.post("/file/message/open", {id: id}, function (resp) {
                    if (resp.code == "success") {
                        app.refreshMessage();
                    } else {
                        alert(data.message);
                    }
                });
            },

            updateMessage: function (message) {
                $.post("/file/message/update", message, function (resp) {
                    console.log(resp);
                    app.refreshMessage();
                })
            }
        }
    });

    app.init();
    app.refreshMessage();
// 文件上传
var BASE_URL = "/static/lib/webuploader"
// 初始化Web Uploader
var uploader = WebUploader.create({

    // 选完文件后，是否自动上传。
    auto: true,

    // swf文件路径
    swf: BASE_URL + '/Uploader.swf',

    // 文件接收服务端。
    server: '/fs_upload/range',

    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: '#filePicker',

    // 需要分片
    chunked: true,
    // 默认5M
    // chunkSize: 1024 * 1024 * 5,
    chunkSize: 1024 * 1024 * 5,
    // 重试次数
    chunkRetry: 10,
    // 文件上传域的name
    fileVal: "file",
    // 不开启并发
    threads: 1,
});

// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
    var $li = $(
            '<div id="' + file.id + '" class="file-item thumbnail">' +
                '<img>' +
                '<div class="info">' + file.name +
                '<span class="finished-tag" id="' + file.id + '-result"></span>' + 
                 '</div>' +
            '</div>'
            ),
        $img = $li.find('img');

    $list = $("#fileList");
    // $list为容器jQuery实例
    $list.append( $li );

    // 创建缩略图
    // 如果为非图片文件，可以不用调用此方法。
    // thumbnailWidth x thumbnailHeight 为 100 x 100
    var thumbnailWidth = 100;
    var thumbnailHeight = 100;
    uploader.makeThumb( file, function( error, src ) {
        if ( error ) {
            $img.replaceWith('<span>不能预览</span>');
            return;
        }

        $img.attr( 'src', src );
    }, thumbnailWidth, thumbnailHeight );
});


// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
    var $li = $( '#uploadProgress' ),
    $percent = $li.find('.progress span');

    // 避免重复创建
    if ( !$percent.length ) {
        $percent = $('<div class="progress"><span></span></div>')
                .appendTo( $li )
                .find('span');
    }

    $percent.css( 'width', percentage * 100 + '%' );
    $percent.text( (percentage * 100).toFixed(2) + '%');
});

uploader.on( 'uploadBeforeSend', function (object, data, headers) {
    $( '#uploadProgress' ).find('.progress').remove();
    data.dirname = "auto";
    data.prefix = "msg";
})

// 文件上传成功，给item添加成功class, 用样式标记上传成功。
uploader.on( 'uploadSuccess', function( file, resp) {
    $( '#uploadProgress' ).find('.progress').remove();
    var $li = $( '#uploadProgress' );
    $('<div class="progress"><span>上传完成</span></div>')
                .appendTo( $li )
                .find('span');
    file.webpath = resp.webpath;
});

// 文件上传失败，显示上传出错。
uploader.on( 'uploadError', function( file ) {
    var $li = $( '#'+file.id ),
        $error = $li.find('div.error');

    // 避免重复创建
    if ( !$error.length ) {
        $error = $('<div class="error"></div>').appendTo( $li );
    }

    $error.text('上传失败');
});

// 完成上传完了，成功或者失败，先删除进度条。
uploader.on( 'uploadComplete', function( file ) {
    var webpath = file.webpath;
    var content = 'file://$name'.replace(/\$name/g, file.webpath);
    app.input += content + "\n";
});

$("#filePickerBtn").on("click", function (event) {
    console.log("select file button click");
    $("#filePicker").click();
})

$("#filePicker").on("change", function (event) {
    console.log(event);
    var fileList = event.target.files; //获取文件对象 
    console.log(fileList);
    if (fileList && fileList.length > 0) {
        uploader.addFile(fileList);
    }
});

</script>

{% end %}